import { App, Space, Button, Tooltip, Dropdown } from "antd";
import { page, del, batDel, save, isLock, findUserRole, saveUserRole } from "@/views/sys/account/api";
import { useTable, useTableDialog } from "@/hooks/useTable";
import CloudTable from "@/component/CloudTable";
import { DeleteOutlined, ShareAltOutlined } from '@ant-design/icons';
import { useEffect } from "react";
import { STATUS_ENUMS, STATUS_OPTIONS } from "./data";
import FormModal from "@/component/FormModal";
import { useFormDialog } from "@/hooks/useForm";
import TableDrawer from "@/component/TableDrawer";
import { getUserId } from "@/utils/storage";

const Account = () => {

    const { message } = App.useApp();

    /**
     * 表单提交后的回调函数
     */
    const onAccountFormCallback = (model) => {
        accountForm.onSubmit(model, accountTable.onReload);
    }

    // 表单操作
    const accountForm = useFormDialog({
        width: 450,
        save: save,
        callback: onAccountFormCallback,
        items: [
            {
                label: '账号',
                name: 'account',
                rules: [
                    { required: true, message: '请输入账户!' },
                    {
                        pattern: /^[A-Za-z0-9_]+$/,
                        message: '账号只能包含字母、数字和下划线'
                    }
                ]
            },
        ],
    });

    const onSaveUserRoleHandler = (model) => {
        saveUserRole(model).then(resp => {
            if (resp?.data) {
                message.success('保存成功');
                roleTableDrawer.isOpenDialog();
            } else {
                message.error('保存失败');
            }
        });
    }

    // 角色抽屉
    const roleTableDrawer = useTableDialog({
        title: '角色',
        isPage: false,
        width: 250,
        reload: findUserRole,
        callback: onSaveUserRoleHandler,
        columns: [
            {
                title: '角色名称',
                dataIndex: 'name',
                key: 'name',
                width: 'auto',
            },
        ],
    });

    const accountTools = () => {
        return (
            <Space>
                <Button type="primary" onClick={() => accountForm.isOpenDialog(undefined, '新增')}>新增</Button>
                <Button type='dashed' style={{ color: 'red' }} onClick={() => accountTable.onBatchRemove(accountTable.selected)}>删除</Button>
            </Space>
        );
    }

    const accountColumns = [
        {
            title: '#',
            key: 'index',
            width: 50,
            align: 'center',
            fixed: 'left',
            render: (val, record, index) => {
                return index + 1;
            }
        },
        {
            title: '账号',
            dataIndex: 'account',
            key: 'account',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '昵称',
            dataIndex: 'nickname',
            key: 'nickname',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '手机',
            dataIndex: 'phone',
            key: 'phone',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            width: 'auto',
            ellipsis: true,
            search: 'default',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            search: 'selected',
            options: STATUS_OPTIONS(),
            // 使用对象映射简化状态判断逻辑
            render: (val, row) => {
                let opts = [];
                let color = { color: 'blue' };

                if (val == 0) {
                    opts = [
                        {
                            label: (
                                <a href='#' onClick={() => isLockHandler(row.id, 1)}>
                                    锁定
                                </a>
                            ),
                            key: 1,
                        },
                        {
                            label: (
                                <a href='#' onClick={() => isLockHandler(row.id, 2)}>
                                    封号
                                </a>
                            ),
                            key: 2,
                        },
                    ];
                } else if (val == 1) {
                    color = { color: 'red' };
                    opts = [{
                        label: (
                            <a href='#' onClick={() => isLockHandler(row.id, 0)}>
                                解锁
                            </a>
                        ),
                        key: 0,
                    }]
                } else if (val == 2) {
                    color = { color: 'red' };
                    opts = [{
                        label: (
                            <a href='#' onClick={() => isLockHandler(row.id, 0)}>
                                解封
                            </a>
                        ),
                        key: 0,
                    }]
                } else {
                    return STATUS_ENUMS[val] || '待激活';
                }
                return (
                    <Dropdown menu={{ items: opts }} trigger={['click']}>
                        <a onClick={e => e.preventDefault()}>
                            <Space style={color}>
                                {STATUS_ENUMS[val]}
                            </Space>
                        </a>
                    </Dropdown>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'id',
            width: 100,
            align: 'center',
            fixed: 'right',
            render: (val) => {
                let userId = getUserId();
                if (userId == 0) {
                    return (
                        <Tooltip title="删除">
                            <Button type="text" size="small" icon={<DeleteOutlined />} style={{ margin: '0 4px', color: 'red' }} onClick={() => accountTable.onRemove(val)} />
                        </Tooltip>
                    );
                } else {
                    return (
                        <>
                            <Tooltip title="分配角色">
                                <Button type="text" size="small" icon={<ShareAltOutlined />} style={{ margin: '0 4px', color: 'blue' }} onClick={() => roleTableDrawer.isOpenDialog(val)} />
                            </Tooltip>
                            <Tooltip title="删除">
                                <Button type="text" size="small" icon={<DeleteOutlined />} style={{ margin: '0 4px', color: 'red' }} onClick={() => accountTable.onRemove(val)} />
                            </Tooltip>
                        </>
                    );
                }
            }
        }
    ];

    const accountTable = useTable({
        reload: page,
        remove: del,
        batchRemove: batDel,
        tools: accountTools,
        columns: accountColumns,
    });

    const isLockHandler = (id, val) => {
        let model = {
            id,
            status: val,
        }
        isLock(model).then(resp => {
            if (resp?.data) {
                message.success('操作成功');
                accountTable.onReload();
            }
        });
    }

    useEffect(() => {
        accountTable.onReload();
    }, []);

    return (
        <>
            <CloudTable props={accountTable} />
            <FormModal props={accountForm} />
            <TableDrawer props={roleTableDrawer} />
        </>
    );
}

export default Account;